import logging
import os
from datetime import datetime
from typing import Optional


class Logger:
    """日志管理器"""
    
    def __init__(self, name: str, level: str = "INFO", log_dir: str = "logs"):
        self.name = name
        self.level = getattr(logging, level.upper(), logging.INFO)
        self.log_dir = log_dir
        self.logger = None
        self._setup_logger()
    
    def _setup_logger(self):
        """设置日志器"""
        # 创建日志目录
        if not os.path.exists(self.log_dir):
            os.makedirs(self.log_dir)
        
        # 创建日志器
        self.logger = logging.getLogger(self.name)
        self.logger.setLevel(self.level)
        
        # 避免重复添加处理器
        if self.logger.handlers:
            return
        
        # 创建格式器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S'
        )
        
        # 文件处理器
        log_file = os.path.join(
            self.log_dir, 
            f"{self.name}_{datetime.now().strftime('%Y%m%d')}.log"
        )
        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(self.level)
        file_handler.setFormatter(formatter)
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(self.level)
        console_handler.setFormatter(formatter)
        
        # 添加处理器
        self.logger.addHandler(file_handler)
        self.logger.addHandler(console_handler)
    
    def info(self, message: str):
        """记录信息级别日志"""
        if self.logger:
            self.logger.info(message)
    
    def error(self, message: str):
        """记录错误级别日志"""
        if self.logger:
            self.logger.error(message)
    
    def warning(self, message: str):
        """记录警告级别日志"""
        if self.logger:
            self.logger.warning(message)
    
    def debug(self, message: str):
        """记录调试级别日志"""
        if self.logger:
            self.logger.debug(message)


def get_logger(name: str, level: str = "INFO") -> Logger:
    """获取日志器实例"""
    return Logger(name, level)
